package com.umeox.watch.moto.chat.ui

import android.content.Context
import android.os.AsyncTask
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.MainThread
import androidx.annotation.WorkerThread
import com.umeox.moto.common.utils.FileUtils
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity
import com.umeox.watch.moto.chat.R
import com.umeox.watch.moto.chat.db.ChatMessage
import com.umeox.watch.moto.chat.db.ContactInfo
import com.umeox.watch.moto.chat.db.MessageDelegate
import com.umeox.watch.moto.chat.proto.ChatMsgProtos
import com.umeox.watch.moto.chat.utils.Constants
import com.umeox.watch.moto.chat.utils.Constants.EXTRA_FILE_PATH
import com.umeox.watch.moto.dataservice.DataProvider
import com.umeox.watch.moto.dataservice.interfaces.IChat
import com.umeox.watch.moto.dataservice.proxy.ChatProxy
import java.lang.Exception
import java.lang.ref.WeakReference

/**
 * Created by Rambo 2021/8/24
 * Describe:
 */
class ShareFileActivity : ThemeAppCompatActivity() {

    private lateinit var mMessageTv: TextView

    private lateinit var mLoadingIv: ImageView

    private lateinit var mRotateAnimation: RotateAnimation

    companion object {
        private const val SHARE_COMPLETE = 0x10
        private const val FINISH_ACTIVITY = 0x12
        private const val SHARE_FAILURE = 0x14
    }

    private var mContactInfo: ContactInfo? = null
    private var isPic = false

    private lateinit var mHandler: Handler

    private var mFilepath: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.act_share_file)
        val intent = intent
        initHandler()
        mContactInfo = intent.getParcelableExtra(Constants.EXTRA_CONTACT)
        mFilepath = intent.getStringExtra(EXTRA_FILE_PATH)
        isPic =
            FileUtils.getFileSuffix(mFilepath).equals("png") || FileUtils.getFileSuffix(mFilepath)
                .equals("jpg")
        mMessageTv = findViewById(R.id.tvMessage)
        mLoadingIv = findViewById(R.id.ivUploading)

        startAnimation()
        if (mContactInfo != null) {
            val uploading =
                java.lang.String.format(getString(R.string.share_to), mContactInfo?.name)
            mMessageTv.text = uploading

            shareFiling()
        }
    }

    private fun initHandler() {
        mHandler = Handler { msg ->
            when (msg.what) {
                SHARE_COMPLETE -> {
                    mMessageTv.setText(R.string.share_completed)
                    mRotateAnimation.cancel()
                    mLoadingIv.clearAnimation()
                    mLoadingIv.setImageResource(R.drawable.icon_share_success)
                    mHandler.sendEmptyMessageDelayed(FINISH_ACTIVITY, 1000)
                }

                FINISH_ACTIVITY -> {
                    finish()
                }

                SHARE_FAILURE -> {
                    mMessageTv.setText(R.string.share_failure)
                    mRotateAnimation.cancel()
                    mLoadingIv.clearAnimation()
                    mLoadingIv.setImageResource(R.drawable.icon_share_fail)
                    mHandler.sendEmptyMessageDelayed(FINISH_ACTIVITY, 1000)
                }
            }
            false
        }
    }


    private fun startAnimation() {
        mRotateAnimation = RotateAnimation(
            0F,  // 起始角度
            359F,  // 终止的角度
            Animation.RELATIVE_TO_SELF,
            0.5f,
            Animation.RELATIVE_TO_SELF,
            0.5f
        )
        mRotateAnimation.duration = 1500
        mRotateAnimation.interpolator = LinearInterpolator()
        mRotateAnimation.repeatCount = Animation.INFINITE
        mLoadingIv.startAnimation(mRotateAnimation)
    }


    private fun shareFiling() {
        val chatMessage = ChatMessage()
        chatMessage.fuid = DataProvider.getHolderId()
        chatMessage.tuid = mContactInfo!!.friendId
        chatMessage.type = if (mContactInfo?.isGroup == true) 1 else 0
        chatMessage.msgType =
            if (isPic) ChatMsgProtos.ChatMsgType.PHOTO_VALUE else ChatMsgProtos.ChatMsgType.VOICE_VALUE
        chatMessage.msgTime = System.currentTimeMillis()
        chatMessage.msgBody = ""
        chatMessage.state = ChatMsgProtos.ChatMsgState.STATE_SENDING_VALUE
        chatMessage.filePath = mFilepath
        if (!isPic) {
            chatMessage.length = FileUtils.getFileDuration(mFilepath)
        }
        SendMsgTask(this, mContactInfo!!, chatMessage)
            .execute()
    }

    inner class SendMsgTask(
        context: Context,
        private val contact: ContactInfo,
        private val chatMessage: ChatMessage
    ) :
        AsyncTask<Void?, Void?, Boolean>() {
        private val actRef: WeakReference<Context> = WeakReference(context)
        private var chatBinder: IChat? = null

        @MainThread
        override fun onPreExecute() {
            val context = actRef.get()
            if (context != null) {
                chatBinder = ChatProxy.fetchBinder()
            }
        }

        @WorkerThread
        override fun doInBackground(vararg voids: Void?): Boolean {
            val context = actRef.get()
            if (context != null) {
                if (chatBinder != null) {
                    //需要先上传文件
                    try {
                        val fileUrl = chatBinder!!.uploadFile(chatMessage.filePath)
                        if (!TextUtils.isEmpty(fileUrl)) {
                            //调用发送接口
                            val msgId = chatBinder!!.sendChatMsg(
                                chatMessage.fuid,
                                chatMessage.tuid,
                                chatMessage.type,
                                chatMessage.msgTime,
                                chatMessage.msgType,
                                fileUrl
                            )
                            if (!TextUtils.isEmpty(msgId)) {
                                chatMessage.msgId = msgId
                                chatMessage.msgBody = fileUrl
                                return true
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }
            return false
        }

        @MainThread
        override fun onPostExecute(result: Boolean) {
            val context = actRef.get()
            if (context != null) {
                if (result) {
                    if (chatMessage.id > 0) {
                        MessageDelegate.getManager().updateChatMessageState(
                            chatMessage,
                            ChatMsgProtos.ChatMsgState.STATE_SENT
                        )
                    } else {
                        chatMessage.state = ChatMsgProtos.ChatMsgState.STATE_SENT_VALUE
                        MessageDelegate.getManager().saveOutMessage(contact, chatMessage, false)
                    }
                    mHandler.sendEmptyMessage(SHARE_COMPLETE)
                } else {
                    if (chatMessage.id > 0) {
                        MessageDelegate.getManager().updateChatMessageState(
                            chatMessage,
                            ChatMsgProtos.ChatMsgState.STATE_SEND_FAILED
                        )
                    } else {
                        chatMessage.state = ChatMsgProtos.ChatMsgState.STATE_SEND_FAILED_VALUE
                        MessageDelegate.getManager().saveOutMessage(contact, chatMessage, false)
                    }
                    mHandler.sendEmptyMessage(SHARE_FAILURE)
                }
            }
        }
    }
}